package com.xmg.p2p.base.service.impl;

import com.xmg.p2p.base.domain.MailVerify;
import com.xmg.p2p.base.domain.Userinfo;
import com.xmg.p2p.base.mapper.MailVerifyMapper;
import com.xmg.p2p.base.mapper.UserinfoMapper;
import com.xmg.p2p.base.service.IVerifyCodeService;
import com.xmg.p2p.base.service.UserinfoService;
import com.xmg.p2p.base.util.BitStatesUtils;
import com.xmg.p2p.base.util.BidConst;
import com.xmg.p2p.base.util.DateUtil;
import com.xmg.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: jinrong-website
 * @BelongsPackage: com.xmg.p2p.base.service.impl
 * @author: Andy
 * @date: 2020.12.2 16:25
 * @Description: UserinfoService的实现类
 * @since JDK 1.8
 */
@Service
public class UserinfoServiceimpl implements UserinfoService {
    private UserinfoMapper userinfoMapper;
    private IVerifyCodeService iVerifyCodeService;
    private MailVerifyMapper mailVerifyMapper;
    @Autowired
    public void setMailVerifyMapper(MailVerifyMapper mailVerifyMapper) {
        this.mailVerifyMapper = mailVerifyMapper;
    }


    @Autowired
    public void setiVerifyCodeService(IVerifyCodeService iVerifyCodeService) {
        this.iVerifyCodeService = iVerifyCodeService;
    }

    @Autowired
    public void setUserinfoMapper(UserinfoMapper userinfoMapper) {
        this.userinfoMapper = userinfoMapper;
    }

    /**
     * 修改用户信息
     * @param userinfo
     */
    public void update(Userinfo userinfo) {
        int i = this.userinfoMapper.updateByPrimaryKey(userinfo);
        if (i == 0){
            throw new RuntimeException("乐观锁失败,"+userinfo.getId());
        }
    }

    /**
     * 添加用户
     * @param userinfo
     */
    public void add(Userinfo userinfo) {
        int i = userinfoMapper.insert(userinfo);
        if (i == 0){
            throw new RuntimeException("乐观锁失败,"+userinfo.getId());
        }
    }

    /**
     * 通过ID获取用户信息
     * @param id
     * @return
     */
    public Userinfo getById(Long id) {
        return userinfoMapper.selectByPrimaryKey(id);
    }

    /**
     * 验证验证码是否正确，并实现绑定手机的功能
     * @param phoneNumber
     * @param verifyCode
     */
    public void bindPhone(String phoneNumber, String verifyCode) {
        // 判断当前用户手否已经绑定手机
        // 通过UserContext获取Session中获取对象
        Userinfo current = this.getById(UserContext.getCurrent().getId());
        // 判断用户绑定手机的状态，如果没有进行验证的合法验证
        if (!current.getIsBindPhone()){
            // 验证验证码合法
            boolean ref = iVerifyCodeService.verify(phoneNumber, verifyCode);
            if (ref){
                // 如果合法，就给用户绑定手机
                // 这里使用到了BitStatesUtils状态工具类中添加状态的方法
//                current.setBitState(
//                        BitStatesUtils.addState(
//                                current.getBitState(),BitStatesUtils.OP_BIND_PHONE
//                        )
//                );
                // 这样写代码长,可以提取到UserInfo类中，在其中添加一个 绑定状态码的方法（addState）
                current.addState(BitStatesUtils.OP_BIND_PHONE);
                current.setPhoneNumber(phoneNumber);
                // 修改用户信息
                this.update(current);
            }else {
                throw new RuntimeException("手机验证失败...");
            }
        }else {
            throw new RuntimeException("手机验证失败...");
        }

    }

    /**
     * 验证邮箱
     * @param uuid
     */
    public void bindEmail(String uuid) {
        //根据uuid查询mailVerify对象
        MailVerify mv = this.mailVerifyMapper.selectByUUID(uuid);
        if (mv != null
                && DateUtil.getBetweenSecond(mv.getSendTime(), new Date()) < BidConst.EMAIL_VALID_DAY * 24 * 3600 ) {
            //如果有 且在有效期内
            //得到用户，如果用户没有绑定邮箱
            Userinfo userinfo = this.userinfoMapper.selectByPrimaryKey(mv.getLogininfoId());
            if ( !userinfo.getIsBindEmail()) {
                //添加邮箱状态码  设置email属性
                userinfo.addState(BitStatesUtils.OP_BIND_EMAIL);
                userinfo.setEmail(mv.getEmail());
                this.update(userinfo);
                return ;
            }
        }else{
            throw new RuntimeException("验证邮箱地址错误!");
        }
    }

    /**
     * 保存用户的信息
     * @param userinfo
     */
    @Override
    public void updateBasicInfo(Userinfo userinfo) {
        // 将此次的用户信息保存到原来的用户中
        // 获取当前的用户
        Userinfo old = this.getById(UserContext.getCurrent().getId());
        old.setEducationBackground(userinfo.getEducationBackground());  // 学历
        old.setKidCount(userinfo.getKidCount());    // 家庭状态
        old.setHouseCondition(userinfo.getHouseCondition());    // 住房信息
        old.setIncomeGrade(userinfo.getIncomeGrade());      // 工资
        old.setMarriage(userinfo.getMarriage());        // 婚姻状态
        // 判断状态码（用来显示后面那个小图片）
        if (!old.getIsBasicInfo()){
            old.addState(BitStatesUtils.OP_BASIC_INFO);
        }
        try {
            this.update(old);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("资料保存出现异常");
        }
    }

    @Override
    public List<Map<String, Object>> autoComplate(String str) {
        return this.userinfoMapper.autoComplate(str);
    }

}
